package com.za.plugin.transfer.func;


import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

// 修改 date_add() 的使用方式，可以参考官方文档
public class DateAddFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains("date_add");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("date_add\\s*\\(", "date_add(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains("date_add(")) {
            int idx = sql.indexOf("date_add(");
            while (idx >= 0) {
                int left = sql.indexOf('(', idx);
                Content expectContent = StrUtil.getExpectContent(sql, left);
                assert expectContent != null;
                String expectStr = expectContent.getExpectStr();
                expectStr = expectStr.replaceAll("-\\s*", "-").replaceAll("\\+\\s*", "+");
                int end = expectContent.getEnd();
                String[] split = expectStr.split(",");

                String initTime = split[0];
                String[] other = split[1].trim().split("\\s+");
                String interval = other[0];
                String num = other[1];
                String timeUnit = other[2];

                String sb = "";
                if (num.charAt(0) == '\'' && num.charAt(num.length() - 1) == '\'') {
                    sb = "date_add( " + initTime + "," + interval + " " + num + " " + timeUnit + " )";
                } else {
                    sb = "date_add( " + initTime + "," + interval + " \'" + num + "\' " + timeUnit + " )";
                }

                sql = sql.substring(0, idx) + sb + sql.substring(end);
                idx = sql.indexOf("date_add(", idx + "date_add(".length());
            }
        }
        return sql;
    }
}
